import {PUSH, POP, ADD, EDIT} from '../actions'

const defaultState = [
  {
    key: 1,
    name: '路飞',
    age: 20,
  },
  {
    key: 2,
    name: '鸣人',
    age: 21,
  },
  {
    key: 3,
    name: '小魔仙',
    age: 22,
  }
];

export const personReducer = (state = defaultState,action) => {// 把数据存储起来
  let newState = JSON.parse(JSON.stringify(state));
  switch (action.type) {
    //action.type  要大写
    case PUSH :
      //深拷贝 最终要返回的是新的数据
      //第一步 : 操作state   添加数据
      //第二步 返回新的state
      if (action.data !== undefined) {
        newState.push(action.data)
      }
      return newState;
    case POP:
      if (action.key !== undefined) {
        newState = state.filter(item => !(item.key === action.key));
      }
      // a-->操作仓库 删除 操作的是新的state
      // b-->操作仓库 编辑 操作的是新的state
      return newState;
    case ADD:
      if (action.obj !== undefined) {
        //state最后的key拿到 +1
        let key = newState[newState.length - 1]['key'] + 1;
        newState.push({...action.obj, key});
        console.log(newState);
        //存储到仓库
      }
      // else {
      //   //throw new Error('obj must give me!!!!');
      // }
      return newState;
    case EDIT:
      if (action.obj !== undefined) {
        // 找到当前的数据
        let index = newState.findIndex(item => item.key === action.obj.key);
        // 操作当前的数据
        newState[index] = action.obj;
      }
      return newState;
    default:
      return state;
  }
};
